package spring.cloud.tasks.api.analyzer;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.api.domain.zooKeeperClusterAndNameSpace.NameSpaceConfiguration;
import spring.cloud.tasks.api.service.TaskService;
import spring.cloud.tasks.common.node.BlockNodePaths;
import spring.cloud.tasks.common.task.TaskIdAndTaskInstanceIdAndTaskTurnIdAndTaskItemIndex;
import spring.cloud.tasks.common.task.TaskItemExecuteRenewalInfo;
import spring.cloud.tasks.common.zookeeper.ZooKeeper;

import java.util.List;

@Slf4j
@Setter
@Getter
public class OutdatedNoRunningTaskAnalyzer {
    private TaskService taskService;


    public void analyzeOutdatedNoRunningTask(NameSpaceConfiguration nameSpaceConfiguration, ZooKeeper zooKeeper, List<OutdatedNoRunningTaskTask> outdatedNoRunningTaskTaskList, String taskId) {
        OutdatedNoRunningTaskTask outdatedNoRunningTaskTask = new OutdatedNoRunningTaskTask(nameSpaceConfiguration.getNameSpace(), taskId);

        checkOutdatedNoRunningJob(zooKeeper, outdatedNoRunningTaskTaskList, outdatedNoRunningTaskTask);
    }

    private void checkOutdatedNoRunningJob(ZooKeeper zooKeeper, List<OutdatedNoRunningTaskTask> outdatedNoRunningTaskTaskList, OutdatedNoRunningTaskTask outdatedNoRunningTaskTask) {
        try {
            List<String> taskItemIndexPathList = BlockNodePaths.getTaskItemIndexPathListList(zooKeeper.getCuratorFramework(), outdatedNoRunningTaskTask.getTaskId());
            if (taskItemIndexPathList != null) {
                for (String taskItemIndexPath : taskItemIndexPathList) {
                    TaskItemExecuteRenewalInfo taskItemExecuteRenewalInfo = BlockNodePaths.getTaskItemExecuteRenewalInfo(zooKeeper, taskItemIndexPath);
                    if (taskItemExecuteRenewalInfo == null) {
                        TaskIdAndTaskInstanceIdAndTaskTurnIdAndTaskItemIndex taskIdAndTaskInstanceIdAndTaskTurnIdAndTaskItemIndex = new TaskIdAndTaskInstanceIdAndTaskTurnIdAndTaskItemIndex();
                        outdatedNoRunningTaskTask.getTaskIdAndTaskInstanceAndTaskItemList().add(taskIdAndTaskInstanceIdAndTaskTurnIdAndTaskItemIndex);
                    }
                }

            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


}
